package persistence;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import model.Account;

public class AccountDAO extends BaseDAO {
	
	public int deleteAllAccount() throws SQLException{
		int retorno;
		String sql = "DELETE FROM account";
		PreparedStatement ps = this.getConnection().prepareStatement(sql);
		retorno = ps.executeUpdate();
		closeConnection();
		return retorno; 
	}
	
	public boolean insertAccount(Account account, boolean closeConnection) throws SQLException{
		String sql = "INSERT INTO account(" +
						"_id, " +
						"title, " +
						"creation_date, " +
						"currency_id, " +
						"total_amount, " +
						"type, " +
						"issuer, " +
						"number, " +
						"sort_order, " +
						"is_active, " +
						"is_include_into_totals, " +
						"last_category_id, " +
						"last_account_id, "+
						"total_limit, " +
						"card_issuer, " +
						"closing_day, " +
						"payment_day, " +
						"last_transaction_date, " +
						"updated_on) " +
						"values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
		PreparedStatement ps = this.getConnection().prepareStatement(sql);
		ps.setInt    (1 , account.getId());
		ps.setString (2 , account.getTitle());
		ps.setLong   (3 , account.getCreationDate());
		ps.setInt    (4 , account.getCurrencyId());
		ps.setLong   (5 , account.getTotalAmount());
		ps.setString (6 , account.getType());
		ps.setString (7 , account.getIssuer());
		ps.setString (8 , account.getNumber());
		ps.setInt    (9 , account.getSortOrder());
		ps.setByte   (10, account.getIsActive());
		ps.setByte   (11, account.getIsIncludeIntoTotals());
		ps.setInt    (12, account.getLastCategoryId());
		ps.setInt    (13, account.getLastAccountId());
		ps.setLong   (14, account.getTotalLimit());
		ps.setString (15, account.getCardIssuer());
		ps.setByte   (16, account.getClosingDay());
		ps.setByte   (17, account.getPaymentDay());
		ps.setLong	 (18, account.getLastTransactionDate());
		ps.setLong	 (19, account.getUpdatedOn());
		boolean retorno = ps.executeUpdate() == 1;
		if(closeConnection){
			closeConnection();
		}
		return retorno;
	}
	
	public int insertListAccount(List<Account> listAccount) throws Exception{
		int ret=0;
		for(int i = 0; i < listAccount.size(); i++) {
			boolean foiInserido;
			foiInserido = insertAccount(listAccount.get(i),false);
			if(foiInserido){
				ret++;
			}
		}
		closeConnection();
		return ret;
	}
}
